<template>
    <BPTable v-if="init" ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="true" :selection-buttons="selectionButtons" @selectionChange="selectionChange">
        <template #$button>
            <a-button type="primary" ghost @click="openBatch">{{ $c('batch', 'import') }}</a-button>
        </template>

        <template #$selection>
            <a-button v-if="resourceStore.hasPermission('devices:device:batch:unbind:tenant')" @click="batchUnbindTenant">{{ $c('unbind', 'owner') }}</a-button>
            <a-button v-if="resourceStore.hasPermission('devices:device:batch:bind:tenant')" type="primary" @click="batchBindTenantVisible = true">{{ $c('bind', 'owner') }}</a-button>
        </template>

        <template #connectStatus="{record}">
            <a-tag v-if="record.connectStatus == 0" :bordered="false" color="error">离线</a-tag>
            <a-tag v-else :bordered="false" color="success">在线</a-tag>
        </template>

        <template #chargeType="{record}">
            {{ chargingTypeMap[record.chargeType] }}
        </template>

        <template #$action='{record}'>
            <BTextButton @click="openDetail(record)">详情</BTextButton>
        </template>
    </BPTable>

    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item label="类型" name="chargeType" :rules="[{required : true, message : '请选择类型'}]">
                <a-select v-model:value="formData.chargeType" :fieldNames="{label : 'name', value : 'code', options : 'children'}" :options="chargingTypeOptions"></a-select>
            </a-form-item>
            <a-form-item label="产品" name="aliProduct" :rules="[{required : true, message : '请选择产品'}]">
                <a-select v-model:value="formData.aliProduct" :fieldNames="{label : 'ProductName', value : 'ProductKey', options : 'children'}" :options="aliProducts"></a-select>
            </a-form-item>
            <a-form-item label="端口数" name="portCount" :rules="[{required : true}]">
                <a-input type="number" :min="0" v-model:value="formData.portCount" />
            </a-form-item>
            <!-- <a-form-item :label="$t('iotSim')" name="simId">
                <FetchSelect v-model="formData.simId" allowClear label-field="cardNo" value-field="id" options-field="children" :fetch="querySim" />
            </a-form-item> -->
            <a-form-item :label="$t('owner')" name="owner">
                <FetchSelect v-model="formData.owner" allowClear label-field="name" value-field="id" options-field="children" :fetch="querySubTenant" />
            </a-form-item>
            <a-form-item v-if="!formData.id" label="注册到阿里云" name="registerAli">
                <a-switch v-model:checked="formData.registerAli" />
            </a-form-item>
        </a-form>
    </BDialog>

    <BDialog v-model:visible='batchVisible' :title='batchDialogTitle' width='600px' :confirm='batchSubmit' @close="closeBatch">
        <a-form ref="batchFormRef" layout="vertical" :model='batchFormData'>
            <a-form-item label="类型" name="chargeType" :rules="[{required : true, message : '请选择类型'}]">
                <a-select v-model:value="batchFormData.chargeType" :fieldNames="{label : 'name', value : 'code', options : 'children'}" :options="chargingTypeOptions"></a-select>
            </a-form-item>
            <a-form-item label="产品" name="aliProduct" :rules="[{required : true, message : '请选择产品'}]">
                <a-select v-model:value="batchFormData.aliProduct" :fieldNames="{label : 'ProductName', value : 'ProductKey', options : 'children'}" :options="aliProducts"></a-select>
            </a-form-item>
            <a-form-item label="端口数" name="portCount" :rules="[{required : true}]">
                <a-input type="number" :min="0" v-model:value="batchFormData.portCount" />
            </a-form-item>
            <a-form-item label="归属" name="owner">
                <FetchSelect v-model="batchFormData.owner" allowClear label-field="name" value-field="id" options-field="children" :fetch="querySubTenant" />
            </a-form-item>
            
            <a-form-item required>
                <template #label>
                    {{ $c('import', 'file') }} 
                    <a-tooltip class="m-l-5">
                        <question-circle-outlined />
                        <template #title>{{ $t('maxUpload', [maxBatchCount]) }}</template>
                    </a-tooltip>
                </template>
                <div>
                    <div class="flex">
                        <a-upload :before-upload="beforeUpload" :max-count="1">
                            <a-button>{{ $c('select', 'file') }}</a-button>
                        </a-upload>
                        <span>
                            <a-button type="text" @click="downloadTemplate">{{ $c('download', 'template') }}</a-button>
                        </span>
                    </div>
                </div>
            </a-form-item>

            <a-form-item label="注册到阿里云" name="registerAli">
                <a-switch v-model:checked="batchFormData.registerAli" />
            </a-form-item>
        </a-form>
    </BDialog>

    <BDialog v-model:visible='batchBindTenantVisible' :title="$c('select', 'owner')" width='600px' :confirm='batchBindSubmit' @close="closeBatchBind">
        <a-form ref="batchBindFormRef" :model='batchBindFormData'>
            <a-form-item :label="$t('owner')" name="owner" :rules="[{required : true, message : $c('please', 'select', 'owner')}]">
                <FetchSelect v-model="batchBindFormData.owner" allowClear label-field="name" value-field="id" options-field="children" :fetch="querySubTenant" />
            </a-form-item>
        </a-form>
    </BDialog>


    <a-drawer width="800px" destroyOnClose v-model:open="isOpenDetail">
        <Detail :device="currentDetail" />
    </a-drawer>

</template>

<script lang='ts' setup>
    import { QuestionCircleOutlined } from '@ant-design/icons-vue';
    import { pageApi, deleteApi, saveApi, saveBatchApi, batchUnbindTenantApi, batchBindTenantApi, ownedDeviceApi, queryProductListApi, chargingTypeApi } from '@/api/devices/Device'
    import { querySimCardApi } from '@/api/devices/IotSim'
    import { useI18nStore } from '@/store/i18n'
    import { useResourceStore } from '@/store/resource'
    import { downloadCsv, readCsv, recursionFn, recursionIndexValues } from '@/utils'
    import { message, Modal } from 'ant-design-vue'
    import { nextTick, ref } from 'vue'
    import FetchSelect from '@/components/FetchSelect.vue'
    import { querySubTenantApi } from '@/api/system/Tenant';
    import { doExport } from './exportData';
    import Detail from './Detail.vue'


    const isOpenDetail = ref(false)
    const currentDetail = ref<any>()
    function openDetail(row) {
        currentDetail.value = row
        isOpenDetail.value = true
    }
    


    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const batchVisible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()
    const batchFormRef = ref()
    const batchDialogTitle = i18n.concat('batch', 'import')

    const file = ref<File>()
    const maxBatchCount = 10000
    const init = ref(false)

    //所选的行
    const selectedKeys = ref<any[]>([])
    function selectionChange(keys:any[], rows:any[]) {
        selectedKeys.value = keys
    }


    //批量绑定
    const batchBindTenantVisible = ref(false)
    const batchBindFormRef = ref()
    const batchBindFormData = ref({
        owner : ''
    })
    
    async function batchBindSubmit() {
        let { owner } = await batchBindFormRef.value.validate()
        const res = await batchBindTenantApi(selectedKeys.value, owner)

        if(res.success) {
            batchBindTenantVisible.value = false
            message.success(i18n.t('executeSuccess'))
            tableRef.value.load()
            
        }else {
            message.error(res.msg)
        }
    }

    function closeBatchBind() {
        batchBindFormRef.value.clearValidate()
        batchBindFormRef.value.resetFields()
        
    }

    //批量解绑
    function batchUnbindTenant() {
        Modal.confirm({
            title : i18n.t('confirmExecute'),
            async onOk() {
                const res = await batchUnbindTenantApi(selectedKeys.value)

                if(res.success) {
                    message.success(i18n.t('executeSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
                
            }
        })
    }



    const chargingTypeOptions = ref<any[]>([])
    const chargingTypeMap = ref<{[key:string]:string}>({})

    const formData = ref({
        id : 0,
        chargeType : '',
        simId : '',
        aliProduct : '',
        owner : '',
        registerAli : false,
        portCount : ''
    })

    const batchFormData = ref({
        chargeType : '',
        owner : '',
        aliProduct : '',
        portCount : '',
        registerAli : false
    })

    const buttons = ref<SearchButton[]>([])
    const selectionButtons = ref<SelectionButton[]>([])

    if(resourceStore.hasPermission('devices:device:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                queryProductList()
                dialogTitle.value = i18n.t('add')
                visible.value = true
            }
        })
    }

    buttons.value.push({
        button : 'export',
        func : () => {
            dialogTitle.value = i18n.t('add')
            visible.value = true
        }
    })

    // if(resourceStore.hasPermission('devices:device:batch:delete')) {
    //     selectionButtons.value.push({
    //         button : 'delete',
    //         func : async () => {
    //             console.log('333333333')
    //         }
    //     })
    // }





    //阿里云产品
    const aliProducts = ref<any[]>([])
    function queryProductList() {
        if(aliProducts.value.length == 0) {
            queryProductListApi().then(res => {
                aliProducts.value = res.data
            })
        }
    }


    async function querySim(query:string|number, init:boolean = false) {
        const params:any = {}

        if(init) {
            if(!query) return
            params.id = query
        }else {
            params.cardNo = query
        }
        
        let res = await querySimCardApi(params)
        return res.data
    }

    async function querySubTenant(query:string|number, init:boolean = false) {
        const params:any = {}

        if(init) {
            if(!query) return
            params.id = query
        }else {
            params.name = query
        }

        let res = await querySubTenantApi(params)
        return res.data
    }

    function openBatch() {
        queryProductList()
        batchVisible.value = true
    }

    function closeBatch() {
        batchFormRef.value.clearValidate()
        batchFormRef.value.resetFields()
        file.value = undefined
        
    }

    function downloadTemplate() {
        downloadCsv('Template_Device', [['portCount', 'simCard']])
    }


    function beforeUpload(e:File) {
        file.value = e
        return false
    }

    async function batchSubmit() {
        let { type, owner, portportCount } = await batchFormRef.value.validate()
        

        if(!file.value) {
            message.error(i18n.t('selectFileTips'))
            return
        }
        const rows = await readCsv(file.value)
        if(rows.length == 0) {
            return
        }

        if(rows.length > maxBatchCount) {
            message.error(i18n.t('maxUpload', [maxBatchCount]))
            return
        }
        for(let i = 0; i < rows.length; i ++) {
            const row = rows[i]
            row.portCount = row.portCount ? Number(row.portCount) : 0
            if(!Number.isInteger(row.portCount) || row.portCount < 0) {
                message.error(i18n.t('portCountTip'))
                return
            }
        }

        let params:any = {
            type : Number(type),
            rows,
        }

        if(owner) {
            params.owner = owner
        }

        if(portportCount) {
            params.portportCount = portportCount
        }

        const res = await saveBatchApi(params)
        if(res.success) {
            closeBatch()
            batchVisible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            message.error(res.msg)
            
        }
        
    }

    function resetForm() {
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    
    async function submit() {
        let { id, chargeType, portCount, simId, owner, ...params} = await formRef.value.validate()
        
        params.chargeType = Number(chargeType)
        if(portCount) {
            params.portCount = Number(portCount)
        }


        params.simId = simId ? Number(simId) : 0

        params.owner = owner ? Number(owner) : 0

        

        if(id) {
            params.id = Number(id)
        }

        

        const res = await saveApi(params)
        if(res.success) {
            resetForm()
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    const columns = ref<Column[]>([
        {
            title : i18n.t('code'),
            dataIndex : 'id',
            align : 'center',
            inSearch : true,
        },

        {
            title : '充电类型',
            dataIndex : 'chargeType',
            align : 'center',
            inSearch : true,
            type : 'select',
            name : 'chargeType',
            labelField : 'name',
            valueField : 'code',
            optionsField : 'children',
            options : chargingTypeOptions,
            attrs : {
                fieldNames : {
                    label : 'name',
                    value : 'code',
                    options : 'children'
                },

                mode : 'multiple'

                //multiple : true,
            }
        },

        {
            title : '端口数',
            dataIndex : 'portCount',
            align : 'center',
        },

        {
            title : '链接状态',
            dataIndex : 'connectStatus',
            align : 'center',
            inSearch : true,
            type : 'select',
            options : [
                {value : 1, label : '在线'},
                {value : 0, label : '离线'}
            ]
        },

        {
            title : i18n.t('owner'),
            dataIndex : 'ownerName',
            align : 'center',
            inSearch : true,
            name : 'owner',
            type : 'fetchSelect',
            valueField : 'id',
            labelField : 'name',
            optionsField : 'children',
            fetchApi : querySubTenant
        },

        {
            title : i18n.t('iotSim'),
            dataIndex : 'simId',
            align : 'center',
            inSearch : true,
            hideInTable : true,
            type : 'fetchSelect',
            valueField : 'id',
            labelField : 'cardNo',
            optionsField : 'children',
            fetchApi : querySim
            
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
            $edit : resourceStore.hasPermission('devices:device:edit') ? (row) => {
                queryProductList()
                dialogTitle.value = i18n.t('edit')
                for(let k in formData.value) {
                    if(k == 'type') {
                        formData.value[k] = String(row[k])
                    }else if(k == 'simId') {
                        if(row[k] != 0) {
                            formData.value[k] = row[k]
                        }
                    }else {
                        if(k == 'pricing' || k == 'paramsRule' || k == 'longitude' || k == 'latitude') {
                            if(row[k] == 0) {
                                formData.value[k] = ''
                                continue
                            }
                        }

                        formData.value[k] = row[k]
                    }
                    
                }
                // formFields.forEach(field => {
                //     if(field.name == 'expireIn') {
                //         field.defaultValue = row[field.name] ? dayjs(row[field.name] * 1000) : ''
                //     }else {
                //         field.defaultValue = row[field.name]
                //     }
                    
                // })

                visible.value = true
            } : undefined,

            $delete :  resourceStore.hasPermission('devices:device:delete') ? (async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }) : undefined
        }
    ])


    

    chargingTypeApi().then(res => {
        if(res.data.length > 0) {
            res.data.forEach(item => {
                chargingTypeMap.value[item.code] = i18n.t(item.name)
                item.code = Number(item.code)
                item.name = i18n.t(item.name)
            })

            let options = recursionFn(res.data, 0, 'id', 'parentId', 'children')


            chargingTypeOptions.value = options
            
            const values = recursionIndexValues(chargingTypeOptions.value, 0, 'code', 'children')
            
            batchFormData.value.chargeType = formData.value.chargeType = values.pop()
        }

        nextTick(() => {
            init.value = true
        })
    })
    
    
</script>

<style lang='scss' module>
    .username{
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
</style>